using System;
using System.Collections.Generic;
using UnityEngine;
using Google.Protobuf;
using Com.Lin.Proto;

namespace GamePlay.Features.Shared
{
    /// <summary>
    /// Protobuf消息映射器，管理消息ID与对应Protobuf类型的映射关系
    /// </summary>
    public class ProtobufMessageMapper
    {
        #region 单例实现

        private static ProtobufMessageMapper _instance;

        public static ProtobufMessageMapper Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new ProtobufMessageMapper();
                }
                return _instance;
            }
        }

        private ProtobufMessageMapper()
        {
            // 初始化映射字典
            _messageTypeMap = new Dictionary<int, Type>();
            _parseFunctionMap = new Dictionary<int, Func<byte[], EventArgs>>();
        }

        #endregion

        #region 字段和属性

        // 消息ID到类型的映射
        private Dictionary<int, Type> _messageTypeMap;

        // 消息ID到解析函数的映射
        private Dictionary<int, Func<byte[], EventArgs>> _parseFunctionMap;

        // 是否开启调试日志
        private bool _debugMode = true;

        /// <summary>
        /// 是否开启调试日志
        /// </summary>
        public bool DebugMode
        {
            get => _debugMode;
            set => _debugMode = value;
        }

        #endregion

        #region 公共方法

        /// <summary>
        /// 注册消息类型和解析函数
        /// </summary>
        /// <typeparam name="T">Protobuf消息类型</typeparam>
        /// <param name="messageId">消息ID</param>
        /// <param name="parseFunction">解析函数</param>
        public void RegisterMessage<T>(int messageId, Func<byte[], EventArgs> parseFunction) where T : IMessage
        {
            if (!_messageTypeMap.ContainsKey(messageId))
            {
                _messageTypeMap.Add(messageId, typeof(T));
                _parseFunctionMap.Add(messageId, parseFunction);

                if (_debugMode)
                {
                    Debug.Log($"[ProtobufMessageMapper] 已注册消息: ID={messageId}, 类型={typeof(T).Name}");
                }
            }
            else
            {
                // 更新已有映射
                _messageTypeMap[messageId] = typeof(T);
                _parseFunctionMap[messageId] = parseFunction;

                if (_debugMode)
                {
                    Debug.LogWarning($"[ProtobufMessageMapper] 更新消息注册: ID={messageId}, 类型={typeof(T).Name}");
                }
            }
        }

        /// <summary>
        /// 检查消息ID是否已注册
        /// </summary>
        /// <param name="messageId">消息ID</param>
        /// <returns>是否已注册</returns>
        public bool IsMessageRegistered(int messageId)
        {
            return _messageTypeMap.ContainsKey(messageId) && _parseFunctionMap.ContainsKey(messageId);
        }

        /// <summary>
        /// 获取消息类型
        /// </summary>
        /// <param name="messageId">消息ID</param>
        /// <returns>消息类型</returns>
        public Type GetMessageType(int messageId)
        {
            if (_messageTypeMap.TryGetValue(messageId, out Type type))
            {
                return type;
            }
            return null;
        }

        /// <summary>
        /// 解析二进制消息为事件参数
        /// </summary>
        /// <param name="messageId">消息ID</param>
        /// <param name="buffer">字节数组</param>
        /// <returns>事件参数</returns>
        public EventArgs ParseMessage(int messageId, byte[] buffer)
        {
            if (_parseFunctionMap.TryGetValue(messageId, out var parseFunction))
            {
                try
                {
                    return parseFunction(buffer);
                }
                catch (Exception ex)
                {
                    Debug.LogError($"[ProtobufMessageMapper] 解析消息失败: ID={messageId}, 错误={ex.Message}");
                }
            }

            if (_debugMode)
            {
                Debug.LogWarning($"[ProtobufMessageMapper] 未找到消息解析函数: ID={messageId}");
            }

            return null;
        }

        /// <summary>
        /// 清除所有消息注册
        /// </summary>
        public void ClearAllRegistrations()
        {
            _messageTypeMap.Clear();
            _parseFunctionMap.Clear();

            if (_debugMode)
            {
                Debug.Log("[ProtobufMessageMapper] 已清除所有消息注册");
            }
        }

        #endregion
    }

    /// <summary>
    /// 消息注册类，用于集中管理所有消息类型的注册
    /// </summary>
    public static class ProtobufMessageRegister
    {
        /// <summary>
        /// 注册所有消息类型
        /// </summary>
        public static void RegisterAllMessages()
        {
            var mapper = ProtobufMessageMapper.Instance;

            // 登录消息
            mapper.RegisterMessage<ReqLoginMessage>(100101, buffer =>
            {
                var loginMessage = ReqLoginMessage.Parser.ParseFrom(buffer);
                return new LoginRequestEventArgs(loginMessage);
            });

            mapper.RegisterMessage<ResLoginMessage>(-100101, buffer =>
            {
                var message = ResLoginMessage.Parser.ParseFrom(buffer);
                return new LoginResponseEventArgs(message);
            });

            Debug.Log("[ProtobufMessageRegister] 已注册所有消息类型");
        }
    }

    // 事件参数类
    public class LoginRequestEventArgs : EventArgs
    {
        public ReqLoginMessage Data { get; private set; }

        public LoginRequestEventArgs(ReqLoginMessage data)
        {
            Data = data;
        }
    }

    public class LoginResponseEventArgs : EventArgs
    {
        public ResLoginMessage Data { get; private set; }

        public LoginResponseEventArgs(ResLoginMessage data)
        {
            Data = data;
        }
    }
}